package com.css.dzj.dzjap.modules.administration.check.service.impl;

import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.common.util.ServiceUtil;
import com.css.dzj.dzjap.modules.administration.check.entity.ApJgxwCheckAction;
import com.css.dzj.dzjap.modules.administration.check.entity.QApJgxwCheckAction;
import com.css.dzj.dzjap.modules.administration.check.mapper.CheckMapper;
import com.css.dzj.dzjap.modules.administration.check.service.CheckService;
import com.css.dzj.dzjap.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.ComparableExpressionBase;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.NumberExpression;
import com.querydsl.core.types.dsl.StringTemplate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CheckServiceImpl implements CheckService {

    @Autowired
    private CheckMapper checkMapper;
    @Autowired
    JPAQueryFactory jpaQueryFactory;
    @Autowired
    ServiceUtil serviceUtil;
    @Override
    public ApJgxwCheckAction getCheck(String actionId) {
        if(StringUtils.isEmpty(actionId)){
            throw new RuntimeException("参数为空");
        }
        QApJgxwCheckAction qcheck = QApJgxwCheckAction.apJgxwCheckAction;
        return jpaQueryFactory
                .selectFrom(qcheck)
                .where(  qcheck.actionId.eq(actionId),
                        qcheck.delFlag.eq(Constant.NO_DELETE)
                )
                .fetchOne();
    }

    @Override
    @Transactional
    public void updateCheck(ApJgxwCheckAction apJgxwCheckAction) {

    }

    @Override
    @Transactional
    public Boolean delCheck(String actionId) {
        if(StringUtils.isEmpty(actionId)){
            return  false;
        }
        QApJgxwCheckAction qcheck = QApJgxwCheckAction.apJgxwCheckAction;
        try{
            jpaQueryFactory
                    .update(qcheck)
                    .set(qcheck.delFlag,Constant.DELETE)
                    .where(
                            qcheck.delFlag.eq(Constant.NO_DELETE),
                            qcheck.actionId.eq(actionId)
                    )
                    .execute();
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    @Transactional
    public String addCheck(ApJgxwCheckAction apJgxwCheckAction) {
        apJgxwCheckAction.setCreatTime(new Date());
        apJgxwCheckAction.setDelFlag(Constant.NO_DELETE);
        checkMapper.save(apJgxwCheckAction);
        return null;
    }

    @Override
    public QueryResults<ApJgxwCheckAction> getAllCheck(Pageable pageable) {
        QApJgxwCheckAction qcheck = QApJgxwCheckAction.apJgxwCheckAction;
        Predicate predicate = qcheck.isNotNull().or(qcheck.isNull());
        predicate = ExpressionUtils.and(predicate, qcheck.delFlag.eq(Constant.NO_DELETE));
        return  jpaQueryFactory
                .selectFrom(qcheck)
                .where(
                        predicate
                )
                .orderBy(qcheck.creatTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }
    /**
     * 多条件分页查询
     */
    @Override
    public QueryResults<ApJgxwCheckAction> getAllContation(Pageable pageable, String superviseItemImplementCode, String checkActionName, String checkActionCode, String checkDate) {
        QApJgxwCheckAction qcheck = QApJgxwCheckAction.apJgxwCheckAction;
        Predicate predicate = qcheck.isNotNull().or(qcheck.isNull());
        predicate = ("".equals(superviseItemImplementCode) || superviseItemImplementCode == null) ? predicate : ExpressionUtils.and(predicate, qcheck.superviseItemImplementCode.like("%"+superviseItemImplementCode+"%"));
        predicate = ("".equals(checkActionName) || checkActionName == null) ? predicate : ExpressionUtils.and(predicate, qcheck.checkActionName.like("%"+checkActionName+"%"));
        predicate = ("".equals(checkActionCode) || checkActionCode == null) ? predicate : ExpressionUtils.and(predicate, qcheck.checkActionCode.like("%"+checkActionCode+"%"));
        predicate = ExpressionUtils.and(predicate, qcheck.delFlag.eq(Constant.NO_DELETE)) ;
        if((!StringUtils.isEmpty(checkDate))){
            Date startDate = new Date();
            Date checkTime=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                checkTime = sf.parse(checkDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, qcheck.checkDate.between(checkTime,checkTime));
        }
        return jpaQueryFactory
                .selectFrom(qcheck)
                .where(predicate)
                .orderBy(
                        qcheck.creatTime.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();

    }

    @Override
    public HashMap getCount() {
        QApJgxwCheckAction q=QApJgxwCheckAction.apJgxwCheckAction;
       List<ApJgxwCheckAction> list= jpaQueryFactory.selectFrom(q).where(q.delFlag.eq(Constant.NO_DELETE)).fetch();
       HashMap map=new HashMap<>();
       for (ApJgxwCheckAction check:list) {
           String address=check.getImplementInstitution();
            System.out.println(address);
           Long count=jpaQueryFactory.select(q.implementInstitution.count()).from(q).
                   where(q.delFlag.eq(Constant.NO_DELETE),q.implementInstitution.eq(address),q.actionId.eq(check.getActionId())).fetchOne();
           Long value=(Long)map.get(address);
           if(value==null) {
               if(count!=0) {
                   map.put(address, count);
               }
           }else {
               value=count.longValue()+value.longValue();
               map.put(address,value);
           }
       }
        return map;
    }

    @Override
    public HashMap getCountByYear(String year) {
        QApJgxwCheckAction q=QApJgxwCheckAction.apJgxwCheckAction;
        Predicate predicate=q.isNotNull().or(q.isNull());
        List<ApJgxwCheckAction> list= jpaQueryFactory.selectFrom(q).where(q.delFlag.eq(Constant.NO_DELETE)).fetch();
        HashMap map=new HashMap<>();
        for (ApJgxwCheckAction check:list) {
            String address=check.getImplementInstitution();
            System.out.println(address);
            ComparableExpressionBase<?> creatYear = q.creatTime.year();
            predicate =ExpressionUtils.and(predicate,((NumberExpression) creatYear).stringValue().eq(year)) ;
            Long count=jpaQueryFactory.select(q.implementInstitution.count()).from(q).
                    where(q.delFlag.eq(Constant.NO_DELETE),q.implementInstitution.eq(address),q.actionId.eq(check.getActionId()),predicate).fetchOne();
            Long value=(Long)map.get(address);
            if(value==null) {
                if(count!=0) {
                    map.put(address, count);
                }
            }else {
                value=count.longValue()+value.longValue();
                map.put(address,value);
            }
        }
        return map;
    }

    @Override
    public Long getOpCheck(HttpServletRequest request) {
        QApJgxwCheckAction q=QApJgxwCheckAction.apJgxwCheckAction;
        /**
         * 获取suser
         */
        R r = serviceUtil.getUserInfoByRequest(request);
        String suserName = "";
        String location = "";
        String address="";
        String userUnit ="";
        String orgName="";
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            /**
             * 获取用户的省份
             */
            orgName = userInfo.getOrgName();

        }
        Long count=jpaQueryFactory.select(q.implementInstitution.count()).from(q)
                .where(q.delFlag.eq(Constant.NO_DELETE),q.implementInstitution.eq(orgName)).fetchOne();
        return count;
    }
    /**
     * 风险预警调用接口，通过行为编号查询
     * @param code
     * @return
     */
    @Override
    public ApJgxwCheckAction getAction(String code) {
        if(StringUtils.isEmpty(code)){
            throw new RuntimeException("参数为空");
        }
        QApJgxwCheckAction qcheck = QApJgxwCheckAction.apJgxwCheckAction;
        return jpaQueryFactory
                .selectFrom(qcheck)
                .where(qcheck.checkActionCode.eq(code),
                        qcheck.delFlag.eq(Constant.NO_DELETE)
                )
                .fetchOne();
    }

    @Override
    public QueryResults<ApJgxwCheckAction> getAll(Pageable pageable, String superviseItemImplementCode, String checkActionName, String checkResult, String checkForm, String checkType, String checkMode, String checkDate) {
        QApJgxwCheckAction q= QApJgxwCheckAction.apJgxwCheckAction;
        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = ("".equals(superviseItemImplementCode) || superviseItemImplementCode == null) ? predicate : ExpressionUtils.and(predicate, q.superviseItemImplementCode.like("%"+superviseItemImplementCode+"%"));
        predicate = ("".equals(checkActionName) || checkActionName == null) ? predicate : ExpressionUtils.and(predicate, q.checkActionName.like("%"+checkActionName+"%"));
        predicate = ("".equals(checkResult) || checkResult == null) ? predicate : ExpressionUtils.and(predicate, q.checkResult.eq(checkResult));
        predicate=(StringUtils.isEmpty(checkForm))?predicate:ExpressionUtils.and(predicate,q.checkForm.eq(checkForm));
        predicate=(StringUtils.isEmpty(checkMode))?predicate:ExpressionUtils.and(predicate,q.checkMode.eq(checkMode));
        predicate=(StringUtils.isEmpty(checkType))?predicate:ExpressionUtils.and(predicate,q.checkType.eq(checkType));
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE)) ;

        /** 只有结束时间 **/
        if(!StringUtils.isEmpty(checkDate)){
            Date endDate1=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                endDate1 = sf.parse(checkDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.checkDate.eq(endDate1));
        }
        return jpaQueryFactory
                .selectFrom(q)
                .where(predicate)
                .orderBy(
                        q.creatTime.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();
    }

    @Override
    public Long getNum() {
        QApJgxwCheckAction q= QApJgxwCheckAction.apJgxwCheckAction;
        return jpaQueryFactory.select(q.actionId.count()).
                from(q).where(q.delFlag.eq(Constant.NO_DELETE)).
                fetchCount();
    }

    @Override
    public List<ApJgxwCheckAction> getList(String superviseItemImplementCode, String checkActionName, String checkResult, String checkForm, String checkType, String checkMode, String checkDate) {
        QApJgxwCheckAction q= QApJgxwCheckAction.apJgxwCheckAction;
        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = ("".equals(superviseItemImplementCode) || superviseItemImplementCode == null) ? predicate : ExpressionUtils.and(predicate, q.superviseItemImplementCode.like("%"+superviseItemImplementCode+"%"));
        predicate = ("".equals(checkActionName) || checkActionName == null) ? predicate : ExpressionUtils.and(predicate, q.checkActionName.like("%"+checkActionName+"%"));
        predicate = ("".equals(checkResult) || checkResult == null) ? predicate : ExpressionUtils.and(predicate, q.checkResult.eq(checkResult));
        predicate=(StringUtils.isEmpty(checkForm))?predicate:ExpressionUtils.and(predicate,q.checkForm.eq(checkForm));
        predicate=(StringUtils.isEmpty(checkMode))?predicate:ExpressionUtils.and(predicate,q.checkMode.eq(checkMode));
        predicate=(StringUtils.isEmpty(checkType))?predicate:ExpressionUtils.and(predicate,q.checkType.eq(checkType));
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE)) ;

        /** 只有结束时间 **/
        if((!StringUtils.isEmpty(checkDate))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                endDate = sf.parse(checkDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.checkDate.loe(endDate));
        }
        return jpaQueryFactory.selectFrom(q).where(predicate).fetch();
    }

    @Override
    public List<ApJgxwCheckAction> getByIds(List<String> ids) {
        return checkMapper.findAllById(ids);
    }

    @Override
    public List<ApJgxwCheckAction> getApList() {

        QApJgxwCheckAction q= QApJgxwCheckAction.apJgxwCheckAction;
        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE));
        return jpaQueryFactory.selectFrom(q).where(predicate).fetch();

    }

}
